package com.siwei.mes.controller.common;

import cn.dev33.satoken.stp.SaLoginConfig;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONArray;
import com.siwei.mes.common.annotation.AnonymousAccess;
import com.siwei.mes.common.result.Json;
import com.siwei.mes.common.util.MapUtils;
import com.siwei.mes.common.util.Md5Utils;
import com.siwei.mes.config.CompanyConfigInterceptor;
import com.siwei.mes.entity.dto.LoginDto;
import com.siwei.mes.entity.system.User;
import com.siwei.mes.entity.vo.LoginVo;
import com.siwei.mes.mapper.system.UserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Map;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * @Description: 登录授权
 * @Version: 1.0
 * @author: chenmaolin
 * @date: 2023/11/21 18:59
 */
@Slf4j
@RestController
@Api(tags = "登录授权接口")
@RequestMapping("auth")
public class AuthController {
    @Resource
    private UserMapper userMapper;


    @ApiOperation("登录接口")
    @PostMapping("login")
    @AnonymousAccess
    public Json login(@RequestBody @Valid LoginVo loginVo) throws NoSuchAlgorithmException {
        String userPhone = loginVo.getUserPhone();
        String password = Md5Utils.encrypt(loginVo.getPassword());
        String device = loginVo.getDevice().trim().toUpperCase();


        if ("levin".equals(userPhone) && Md5Utils.encrypt("levin123456").equals(password)) {
            User user = new User();
            user.setId((long) 99999999)
                    .setUserNo("levin")
                    .setUserName("levin")
                    .setUserPhone("levin")
                    .setPassword("levin123456")
                    .setRoleId(5L)
                    .setRoleName("管理员")
                    .setJob("超级管理员").setUpdateTime(new Date())
                    .setTestProjectJson(this.getTestProjectJson());

            LoginDto loginDto = this.payloadLoginDto(user, password, device);
            return Json.succ().data(loginDto);
        } else {
            /**判断用户信息是否存在*/
            User user = userMapper.selectByUserPhone(userPhone);
            assertTrue(user == null, "用户不存在!");
            user = userMapper.selectByPhoneAndPassword(userPhone, password);
            assertTrue(user == null, "用户名密码错误!");
            LoginDto loginDto = this.payloadLoginDto(user, password, device);
            return Json.succ().data(loginDto);
        }
    }


    public JSONArray getTestProjectJson() {
        String str = "[{\"no\": \"1\", \"name\": \"水泥\"}, {\"no\": \"2\", \"name\": \"粉煤灰\"}, {\"no\": \"3\", \"name\": \"矿渣粉\"}, {\"no\": \"4\", \"name\": \"粗骨料\"}, {\"no\": \"5\", \"name\": \"细骨料\"}, {\"no\": \"6\", \"name\": \"外加剂\"}, {\"no\": \"7\", \"name\": \"混凝土\"}]";
        return JSONArray.parseArray(str);
    }

    /**
     * 组装登录信息
     *
     * @param user     用户信息
     * @param password 密码
     * @param device   登录端
     * @return
     */
    private LoginDto payloadLoginDto(User user, String password, String device) {
        LoginDto loginDto = new LoginDto().setUserId(user.getId()).setUserName(user.getUserName())
                .setUserPhone(user.getUserPhone()).setPassword(password)
                .setAvatar(user.getAvatar()).setJob(user.getJob())
                .setRoleId(user.getRoleId()).setRoleName(user.getRoleName()).setExperimentCompany(CompanyConfigInterceptor.getCompanyConfig(1).getCompanyName());

        loginDto.setUserLastUpdateTime(user.getUpdateTime().getTime());

        /**把试验项目权限加进来*/
        loginDto.setTestProjectJson(user.getTestProjectJson());
        /**把协会用户名加进来*/
        loginDto.setSocietyUserName(user.getSocietyUserName());

        loginDto.setUserSignImg(user.getUserSignImg());

        Map<String, Object> userMap = MapUtils.beanToMap(loginDto);
        SaLoginModel saLoginModel = SaLoginConfig.setExtraData(userMap);
        saLoginModel.setDevice(device);

        StpUtil.login(user.getId(), saLoginModel);

        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        loginDto.setTokenName(tokenInfo.getTokenName());
        loginDto.setTokenValue(tokenInfo.getTokenValue());
        return loginDto;
    }
}
